package com.example.springbootdemo.server;

import com.example.springbootdemo.mapper.UserMapper;
import com.example.springbootdemo.model.Result;
import com.example.springbootdemo.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Service
@Slf4j
public class UserServer {
    @Resource
    private UserMapper userMapper;

    public Result findAll() {
        return Result.success(userMapper.findAll());
    }

    public Result insertUser(UserModel userModel) {
        userModel.setId(UUID.randomUUID().toString().replace("-", ""));
        try {
            return Result.success(userMapper.insertUser(userModel));
        } catch (Exception e) {
            log.error("用户名存在，主键冲突：{} \n {}", userModel.getUserName(), e.toString());
            if (e.toString().contains("Duplicate")) {
                return Result.error(null, "用户名已存在");
            }
            return Result.error(null, "系统异常，请联系管理员");
        }
    }

    public Result findUserById(String id) {
        UserModel userById = userMapper.findUserById(id);
        return Result.success(userById);
    }

    public Result updateUserById(UserModel userModel) {
        return Result.success(userMapper.updateUserById(userModel));
    }

    public Result deleteUserById(String id) {
        log.info("delete user by id {}", id);
        if (userMapper.deleteUserById(id) > 0) {
            return Result.success(null, "删除成功");
        }
        return Result.error(null, "系统异常删除失败");
    }

    public Result seachUser(UserModel userModel) {
        return Result.success(userMapper.seachUser(userModel));
    }
}
